#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pycurl
import StringIO
import os
import sys


def getPMC(id, ids):
    url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
    buf = StringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.POST, 1)
    c.setopt(c.URL, url)
    c.setopt(pycurl.HTTPPOST, [('db', 'pmc'), ('id', ids), ('retmode', 'xml')])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    outfile = open("pmc_id_" + id + ".xml", "w")
    outfile.write(buf.getvalue())
    outfile.close()
    buf.close()
    print "PMC meta task id " + id + " has been successfully downloaded."


if __name__ == '__main__':
    ids = ""
    infile = open(sys.argv[1], 'r')
    for line in infile:
        line = line.rstrip()
        ids += line + ","
    infile.close()
    ids = ids[:-1]
    id = sys.argv[1][:-4].split("_")[2]
    print "Submit PMC meta task id " + id + "."
    getPMC(id, ids)
    name = "pmc_id_" + id
    os.system("tar czf " + name + ".tar.gz " + name + ".xml --remove-files")
    os.system("md5sum " + name + ".tar.gz >" + name + ".tar.gz.md5")
    os.system("mv " + name + ".tar.gz " + name + ".tar.gz.complete")
    os.system("rm -rf "+sys.argv[1])
    print "Finish PMC meta task id " + id + "."
